#include "SeqList.h"

Status InitList(SeqList *L)
{
  (*L).elem = (ElemType *)malloc(LIST_INI_SIZE * sizeof(ElemType));
  if ((*L).elem == NULL)
  {
    exit(OVERFLOW);
  }
  (*L).length = 0;
  (*L).listsize = LIST_INI_SIZE;
  return OK;
}

Status DestroyList(SeqList *L)
{
  if (L == NULL || (*L).elem == NULL)
  {
    return ERROR;
  }
  free((*L).elem);
  (*L).elem = NULL;
  (*L).length = 0;
  (*L).listsize = 0;
  return OK;
}

Status ClearList(SeqList *L)
{
  if (L == NULL || (*L).elem == NULL)
  {
    return ERROR;
  }
  (*L).length = 0;
  return OK;
}

Status ListEmpty(SeqList L)
{
  return L.length == 0 ? TRUE : FALSE;
}

int ListLength(SeqList L)
{
  return L.length;
}

Status GetElementAt(SeqList L, int i, ElemType *e)
{
  if (i < 1 || i > L.length)
  {
    return ERROR;
  }
  *e = L.elem[i - 1];
  return OK;
}

int LocateElem(SeqList L, ElemType e, Status(Compare)(ElemType, ElemType))
{
  int i;
  ElemType *p;
  if (L.elem == NULL)
  {
    return ERROR;
  }
  i = 1;
  p = L.elem;
  while (i <= L.length && !Compare(*p++, e))
  {
    ++i;
  }
  if (i <= L.length)
  {
    return i;
  }
  else
  {

    return 0;
  }
}

Status PriorElemet(SeqList L, ElemType cur_e, ElemType *pre_e)
{
  int i;
  if (L.elem == NULL || L.length < 2)
  {
    return ERROR;
  }
  i = 0;
  while (i < L.length && L.elem[i] != cur_e)
  {
    ++i;
  }
  if (i == 0 || i >= L.length)
  {
    return ERROR;
  }
  *pre_e = L.elem[i - 1];
  return OK;
}

Status NextElement(SeqList L, ElemType cur_e, ElemType *nxt_e)
{
  int i;
  if (L.elem == NULL || L.length < 2)
  {
    return ERROR;
  }
  i = 0;
  while (i < L.length - 1 && L.elem[i] != cur_e)
  {
    ++i;
  }
  if (i >= L.length - 1)
  {
    return ERROR;
  }
  *nxt_e = L.elem[i + 1];
  return OK;
}

Status ListInsert(SeqList *L, int i, ElemType e)
{
  ElemType *newbase;
  ElemType *p, *q;
  if (L == NULL || (*L).elem == NULL)
    return ERROR;
  if (i < 1 || i > (*L).length + 1)
    return ERROR;
  if ((*L).length >= (*L).listsize)
  {
    newbase = (ElemType *)realloc((*L).elem, ((*L).listsize + LISTINCREMENT) * sizeof(ElemType));
    if (newbase == NULL)
      exit(OVERFLOW);
    (*L).elem = newbase;
    (*L).listsize += LISTINCREMENT;
  }
  q = &(*L).elem[i - 1];
  for (p = &(*L).elem[(*L).length - 1]; p >= q; --p)
    *(p + 1) = *p;
  *q = e;
  (*L).length++;
  return OK;
}